package io.renren.modules.reception.controller;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.util.concurrent.AtomicDouble;
import io.renren.common.exception.RRException;
import io.renren.modules.member.service.TStoreMemberRechargeRecordService;
import io.renren.modules.reception.entity.vo.CountTotalVo;
import io.renren.modules.reception.entity.vo.ReserveVo;
import io.renren.modules.reception.service.*;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.reception.entity.TStoreChangeWorkRecordEntity;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-03-17 22:17:41
 */
@RestController
@RequestMapping("reception/tstorechangeworkrecord")
public class TStoreChangeWorkRecordController extends AbstractController {
    @Autowired
    private TStoreChangeWorkRecordService tStoreChangeWorkRecordService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private TStoreOrderRecordService storeOrderRecordService;
    @Autowired
    private TStoreFastfoodRecordService storeFastfoodRecordService;
    @Autowired
    private TStoreTakeoutRecordService storeTakeoutRecordService;
    @Autowired
    private TStoreReserveDeskService storeReserveDeskService;
    @Autowired
    private TStoreMemberRechargeRecordService storeMemberRechargeRecordService;

    private static final AtomicInteger sanKeNumber = new AtomicInteger();
    private static final AtomicDouble sanKeTotalMoney = new AtomicDouble();
    private static final AtomicInteger memberNumber = new AtomicInteger();
    private static final AtomicDouble memberTotalMoney = new AtomicDouble();
    private static final AtomicInteger accountNumber = new AtomicInteger();
    private static final AtomicDouble accountTotalMoney = new AtomicDouble();
    private static Double reserveTotalMoney = 0.0;
    private static int reserveNumber = 0;
    private static Double memberRechargeMoney = 0.0;
    private static Double devolutionCash = 0.0;

    private static volatile CountDownLatch countDownLatch = new CountDownLatch(4);
    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("reception:tstorechangeworkrecord:list")
    public R list(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        PageUtils page = tStoreChangeWorkRecordService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("reception:tstorechangeworkrecord:info")
    public R info(@PathVariable("id") Long id){
		TStoreChangeWorkRecordEntity tStoreChangeWorkRecord = tStoreChangeWorkRecordService.getById(id);

        return R.ok().put("tStoreChangeWorkRecord", tStoreChangeWorkRecord);
    }
    /**
     * 交班数据
     */
    @RequestMapping("/changeWorkData")
    public R changeWorkData(){
        //接班时间
        String key = "on_duty_user_" + getUserId() + "_" + getSeller();
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        if (entries.get("OnDutyTime") == null){
            return R.error("交班数据出现异常");
        }
        String format = DateUtil.format((Date) entries.get("OnDutyTime"), "yyyy-MM-dd HH:mm:ss");
        //消费(散客，会员，记账单位)
        Map<String,Object> map = new HashMap<>();
        map.put("sellerId",getSeller());
        map.put("time",format);
        map.put("userId",getUserId());
        List<CountTotalVo> tangShiList = storeOrderRecordService.sumReallyGet(map);
        int sanKeNumber = 0;
        Double sanKeTotalMoney = 0.0;
        int memberNumber = 0;
        Double memberTotalMoney = 0.0;
        int accountNumber = 0;
        Double accountTotalMoney = 0.0;
        //支付方式

        for (CountTotalVo countTotalVo : tangShiList){
            //散客
            if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
                sanKeNumber++;
                sanKeTotalMoney += countTotalVo.getReallyGet();
            }
            //会员
            if (countTotalVo.getMemberId() != null){
                memberNumber++;
                memberTotalMoney += countTotalVo.getReallyGet();
            }
            //记账单位
            if (countTotalVo.getAccountId() != null){
                accountNumber++;
                accountTotalMoney += countTotalVo.getReallyGet();
            }
        }
        List<CountTotalVo> fastFoodList = storeFastfoodRecordService.sumReallyGet(map);
        for (CountTotalVo countTotalVo : fastFoodList){
            //散客
            if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
                sanKeNumber++;
                sanKeTotalMoney += countTotalVo.getReallyGet();
            }
            //会员
            if (countTotalVo.getMemberId() != null){
                memberNumber++;
                memberTotalMoney += countTotalVo.getReallyGet();
            }
            //记账单位
            if (countTotalVo.getAccountId() != null){
                accountNumber++;
                accountTotalMoney += countTotalVo.getReallyGet();
            }
        }
        List<CountTotalVo> takeOutList = storeTakeoutRecordService.sumReallyGet(map);
        for (CountTotalVo countTotalVo : takeOutList){
            //散客
            if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
                sanKeNumber++;
                sanKeTotalMoney += countTotalVo.getReallyGet();
            }
            //会员
            if (countTotalVo.getMemberId() != null){
                memberNumber++;
                memberTotalMoney += countTotalVo.getReallyGet();
            }
            //记账单位
            if (countTotalVo.getAccountId() != null){
                accountNumber++;
                accountTotalMoney += countTotalVo.getReallyGet();
            }
        }

        //预定餐桌个数和押金
        ReserveVo reserveVo = storeReserveDeskService.total(map);
        Double reserveTotalMoney = 0.0;
        int reserveNumber = 0;
        if (reserveVo != null){
            reserveTotalMoney = reserveVo.getTotalDeposit();
            reserveNumber = reserveVo.getTotalCount();
        }

        //会员充值总额
        Double memberRechargeMoney = storeMemberRechargeRecordService.memberRechargeMoney(map);
        if (memberRechargeMoney == null){
            memberRechargeMoney = 0.0;
        }
        if (reserveTotalMoney == null){
            reserveTotalMoney = 0.0;
        }

        //前班结余
        Double devolutionCash = tStoreChangeWorkRecordService.devolutionCash(map);

        Double totalMoney = memberTotalMoney + sanKeTotalMoney +
                accountTotalMoney+reserveTotalMoney+memberRechargeMoney;
        int totalNumber = memberNumber + sanKeNumber + accountNumber;
        String endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("sanKeNumber",sanKeNumber);
        map1.put("memberNumber",memberNumber);
        map1.put("accountNumber",accountNumber);
        map1.put("memberTotalMoney",memberTotalMoney);
        map1.put("sanKeTotalMoney",sanKeTotalMoney);
        map1.put("accountTotalMoney",accountTotalMoney);
        map1.put("totalMoney",totalMoney);
        map1.put("reserveTotalMoney",reserveTotalMoney);
        map1.put("reserveNumber",reserveNumber);
        map1.put("memberRechargeMoney",memberRechargeMoney);
        map1.put("startTime",format);
        map1.put("endTime",endTime);
        map1.put("user",entries);
        map1.put("totalNumber",totalNumber);
        map1.put("devolutionCash",devolutionCash);

        return R.ok().put("changeWorkInfo",map1);
    }

//    /**
//     * 交班数据
//     */
//    @RequestMapping("/changeWorkData")
//    public R changeWorkData() throws InterruptedException {
//        String key = "on_duty_user_" + getUserId() + "_" + getSeller();
//        //接班时间
//        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
//        if (entries.get("OnDutyTime") == null){
//            return R.error("交班数据出现异常");
//        }
//        String format = DateUtil.format((Date) entries.get("OnDutyTime"), "yyyy-MM-dd HH:mm:ss");
//        Map<String,Object> map = new HashMap<>();
//        map.put("sellerId",getSeller());
//        map.put("time",format);
//        map.put("userId",getUserId());
//        ExecutorService executorService = Executors.newFixedThreadPool(3);
//        executorService.submit(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //消费(散客，会员，记账单位)
//                    List<CountTotalVo> tangShiList = storeOrderRecordService.sumReallyGet(map);
//                    for (CountTotalVo countTotalVo : tangShiList){
//                        //散客
//                        if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
//                            sanKeNumber.addAndGet(1);
//                            sanKeTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //会员
//                        if (countTotalVo.getMemberId() != null){
//                            memberNumber.addAndGet(1);
//                            memberTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //记账单位
//                        if (countTotalVo.getAccountId() != null){
//                            accountNumber.addAndGet(1);
//                            accountTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }finally {
//                    countDownLatch.countDown();
//                }
//            }
//        });
//
//        executorService.submit(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    List<CountTotalVo> fastFoodList = storeFastfoodRecordService.sumReallyGet(map);
//                    for (CountTotalVo countTotalVo : fastFoodList){
//                        //散客
//                        if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
//                            sanKeNumber.addAndGet(1);
//                            sanKeTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //会员
//                        if (countTotalVo.getMemberId() != null){
//                            memberNumber.addAndGet(1);
//                            memberTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //记账单位
//                        if (countTotalVo.getAccountId() != null){
//                            accountNumber.addAndGet(1);
//                            accountTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }finally {
//                    countDownLatch.countDown();
//                }
//            }
//        });
//
//        executorService.submit(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    List<CountTotalVo> takeOutList = storeTakeoutRecordService.sumReallyGet(map);
//                    for (CountTotalVo countTotalVo : takeOutList){
//                        //散客
//                        if (countTotalVo.getAccountId() == null && countTotalVo.getMemberId() == null){
//                            sanKeNumber.addAndGet(1);
//                            sanKeTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //会员
//                        if (countTotalVo.getMemberId() != null){
//                            memberNumber.addAndGet(1);
//                            memberTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                        //记账单位
//                        if (countTotalVo.getAccountId() != null){
//                            accountNumber.addAndGet(1);
//                            accountTotalMoney.addAndGet(countTotalVo.getReallyGet());
//                        }
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }finally {
//                    countDownLatch.countDown();
//                }
//            }
//        });
//
//        executorService.submit(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //预定餐桌个数和押金
//                    ReserveVo reserveVo = storeReserveDeskService.total(map);
//                    if (reserveVo != null){
//                        reserveTotalMoney = reserveVo.getTotalDeposit();
//                        reserveNumber = reserveVo.getTotalCount();
//                    }
//                    //会员充值总额
//                    memberRechargeMoney = storeMemberRechargeRecordService.memberRechargeMoney(map);
//                    //前班结余
//                    devolutionCash = tStoreChangeWorkRecordService.devolutionCash(map);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }finally {
//                    countDownLatch.countDown();
//                }
//            }
//        });
//
//        countDownLatch.await();
//        executorService.shutdown();
//
//        if (memberRechargeMoney == null){
//            memberRechargeMoney = 0.0;
//        }
//        if (reserveTotalMoney == null){
//            reserveTotalMoney = 0.0;
//        }
//
//        Double totalMoney = memberTotalMoney.get() + sanKeTotalMoney.get() +
//                accountTotalMoney.get()+reserveTotalMoney+memberRechargeMoney;
//        int totalNumber = memberNumber.get() + sanKeNumber.get() + accountNumber.get();
//        String endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
//        Map<String,Object> map1 = new HashMap<>();
//        map1.put("sanKeNumber",sanKeNumber.get());
//        map1.put("memberNumber",memberNumber.get());
//        map1.put("accountNumber",accountNumber.get());
//        map1.put("memberTotalMoney",memberTotalMoney.get());
//        map1.put("sanKeTotalMoney",sanKeTotalMoney.get());
//        map1.put("accountTotalMoney",accountTotalMoney.get());
//        map1.put("totalMoney",totalMoney);
//        map1.put("reserveTotalMoney",reserveTotalMoney);
//        map1.put("reserveNumber",reserveNumber);
//        map1.put("memberRechargeMoney",memberRechargeMoney);
//        map1.put("startTime",format);
//        map1.put("endTime",endTime);
//        map1.put("user",entries);
//        map1.put("totalNumber",totalNumber);
//        map1.put("devolutionCash",devolutionCash);
//
//        sanKeNumber.set(0);
//        sanKeTotalMoney.set(0.0);
//        memberNumber.set(0);
//        memberTotalMoney.set(0.0);
//        accountNumber.set(0);
//        accountTotalMoney.set(0.0);
//        reserveTotalMoney = 0.0;
//        reserveNumber = 0;
//        memberRechargeMoney = 0.0;
//        devolutionCash = 0.0;
//        return R.ok().put("changeWorkInfo",map1);
//    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("reception:tstorechangeworkrecord:save")
    public R save(@RequestBody TStoreChangeWorkRecordEntity tStoreChangeWorkRecord){
		tStoreChangeWorkRecordService.save(tStoreChangeWorkRecord);
		//删除当班信息
        String onDutyInfo = "on_duty_user_" + getUserId() + "_" + getSeller();
        redisTemplate.delete(onDutyInfo);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("reception:tstorechangeworkrecord:update")
    public R update(@RequestBody TStoreChangeWorkRecordEntity tStoreChangeWorkRecord){
		tStoreChangeWorkRecordService.updateById(tStoreChangeWorkRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("reception:tstorechangeworkrecord:delete")
    public R delete(@RequestBody Long[] ids){
		tStoreChangeWorkRecordService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
